#ifndef STRINGMAP_H_
#define STRINGMAP_H_

#include <e32base.h>

/// Class for associating data with strings, not for large amounts of data
template<typename T, typename Des = TDesC8, typename Buf = RBuf8>
class RStringMap
    {
public:
    
    void Close()
        {
        for(TInt i = 0; i < iArray.Count(); ++i)
            { iArray[i].Close(); }
        iArray.Close();
        }
    
    void InsertL(Des const & aKey, T * aValue)
        {
        REntry entry;
        CleanupClosePushL(entry);
        entry.CreateL(aKey, aValue);
        iArray.InsertInOrderL(entry, &REntry::Compare);
        CleanupStack::Pop(&entry);
        }
    
    T * FindL(Des const & aKey)
        {
        TInt pos = iArray.FindInOrder(aKey, &REntry::KeyCompare);
        if(pos >= 0) { return iArray[pos].Value(); }
        else if(pos == KErrNotFound) { return NULL; }
        else { User::Leave(pos); }
        }
    
private:

    class REntry
        {
    public:
        void CreateL(Des const & aKey, T * aValue)
            { iKey.CreateL(aKey); iValue = aValue; } 
        void Close() { iKey.Close(); delete iValue; }
        
        T * Value() { return iValue; }
        
        static TInt KeyCompare(Des const * aKey, REntry const & aEntry)
            { return aEntry.iKey.Compare(*aKey); }
        
        static TInt Compare(REntry const & aLhs, REntry const & aRhs)
            { return aLhs.iKey.Compare(aRhs.iKey); }
        
    private:
        Buf iKey;
        T * iValue;
        };
    
    RArray<REntry> iArray;
    };

#endif /* STRINGMAP_H_ */
